//
//  Yahoo_Mobile_History.m
//  MacStockApp
//
//  Created by 英傑 翁 on 12/3/30.
//  Copyright (c) 2012年 翁英傑. All rights reserved.
//
#import "XX_XQData_History.h"
#import "Yahoo_Mobile_History.h"
#import "GBTableColumnHeader.h"
#import "GBTableColumnHeader_basicSqlite.h"
#import "GBTableColumnHeader_quote.h"
#import "GBTableColumnHeader_2Row3Row.h"
#import "GBTableColumnHeader_node.h" 
#import "GBTableColumnHeader_position.h"  
#import "GBTableColumnHeader_position_bottom_sumaverage.h"  
#import "GBTableColumnHeader_Indicator.h"  
#import "GBTableColumnHeader_signal.h"  
#import "GBTableColumnHeader_ObjectOtherKey.h"  
#import "GBall.h"
#import "XXcrackServerRequest.h"

@implementation Yahoo_Mobile_History

@synthesize delgeate;

-(id)init_With_Code:(NSString *)codea file_code:(NSString *)file_code table_quote_date:(NSDate *)dateq timezone:(NSString *)tz is_have_to_reload_data:(BOOL)have_to_reload{
	
    if(self=[super init])
	{
        
         
        have_to_reload_data=have_to_reload;        
        code=codea;
        
        read_write_file_code=file_code;
        
        table_quote_date=dateq;
        
        timezone=tz;
        
        [code retain];
        [read_write_file_code retain];
        [table_quote_date retain];
        [timezone retain];        
        
    }
	
	return self;
}

-(void)dealloc{
    if (code) {
        [code release]; 
    }
    if (read_write_file_code) {
        [read_write_file_code release];
    }
    if (table_quote_date) {
        [table_quote_date release];
    }
    if (timezone) {
        [timezone release];
    }
    
    [super dealloc];
}

- (void)main 
{ 
     if (have_to_reload_data) {
         //一次全部下載的年限
         //int download_year;
         // download_year=10;
         
         //歷史資料 含時間序列 與最後一筆的時間與收盤價 及此段時間內最大值與最低值
         NSMutableDictionary *all_history_data;    
         //如果有xq資料
         if ([XX_XQData_History isHaveXQ_Dairly_Data:read_write_file_code]) {
             
             all_history_data=[XX_XQData_History read_XQ_Dairly_Data:read_write_file_code _code:code _timezone:timezone];
             
         }
         else{
             
             //歷史檔案路徑
             NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
             NSString *Path_HistoryData  ;
             Path_HistoryData=[prefs objectForKey:Defaults_Path_HistoryData];
             
             
             NSString *filename;
             filename=[NSString stringWithFormat: @"%@.plist",read_write_file_code];
             NSString * write_FilepathnName= [Path_HistoryData stringByAppendingPathComponent:filename]  ;
             
             //1.歷史資料檔案處理
             //下載歷史全部資料
             {
                 
                 all_history_data=[self Get_hisstory_data_3y];
                 
                 //儲存資料
                 if (all_history_data!=nil) {
                     [all_history_data writeToFile:write_FilepathnName atomically:YES];
                 }
                 
             }
             
             
             //2.比較最後一筆歷史資料與報價表時間上差異再來決定是否要利用最近五日tick資料來補缺額的時間
             {
                 
                 //已經取得的歷史資列序列最後一筆日期 理論上是網路上最完整可以取得的資料
                 NSDate *history_lastdate;
                 history_lastdate=  [all_history_data objectForKey:@"last_his_date"]  ;
                 
                 int int_history_lastdate;
                 int int_table_quote_date;
                 int_history_lastdate=[self convert_NSDate_to_int:history_lastdate];
                 int_table_quote_date=[self convert_NSDate_to_int:table_quote_date];
                 
                 
                 NSLog(@"歷史資料表上最後日期=%i",  int_history_lastdate  );
                 NSLog(@"報價表上最新日期=%i",  int_table_quote_date  );
                 
                 //需要回補缺額資料=>表示網路上的歷史資料有缺
                 if (int_table_quote_date-int_history_lastdate>=2) {
                     
                     NSLog(@"需要回補缺額資料=>表示網路上的歷史資料有缺");
                     
                     //取出最近五日資料
                     NSMutableArray *ARRAY_5D;
                     ARRAY_5D=[self Get_5d_hisstory_data];
                     
                     if (ARRAY_5D) {
                         //將分時資料轉成的五日時間序列資料全部取出
                         for (NSMutableDictionary *rrd in ARRAY_5D ) {
                             
                             int get_5day_date;
                             get_5day_date=[self convert_NSDate_to_int:[rrd objectForKey:HIS_basic_date]];
                             
                             //比較只需要在歷史最後ㄧ日與報價日中間的需要加入
                             if (int_history_lastdate<get_5day_date && get_5day_date< int_table_quote_date) {
                                 NSLog(@"比較只需要在歷史最後ㄧ日與報價日中間的需要加入=%@ %@ %@ %@ %@ %@",[rrd objectForKey:HIS_basic_date],[rrd objectForKey:HIS_basic_open],[rrd objectForKey:HIS_basic_close],[rrd objectForKey:HIS_basic_high],[rrd objectForKey:HIS_basic_low],[rrd objectForKey:HIS_basic_vol] );
                                 
                                 [[all_history_data objectForKey:@"his_data"] addObject:rrd ];
                             }
                             
                         }
                         
                         
                     }
                     
                     
                     
                     
                 }
                 //不需要回補缺額 =>表示網路上的歷史資料完整    
                 else {
                     //不需要回補缺額
                     NSLog(@"不需要回補缺額 =>表示網路上的歷史資料完整");
                 }
                 
             }
             
             
             
             
             
         }
         
        
         
         //2.將整理好的開收高低成交量資料傳出來
         NSLog(@"His_Data_Finished before end=%@",code);
         [(Data_Model *)delgeate performSelectorOnMainThread:@selector(His_Data_Finished:) withObject:all_history_data waitUntilDone:YES];        
     }
     else {
         NSLog(@"His_Data_Finished before end no data=%@",code);         
         
         NSMutableDictionary *out_dic=[[[NSMutableDictionary alloc] init] autorelease];
         [out_dic setObject:code forKey:DB_object_sqlite_basic_code];        
         [(Data_Model *)delgeate performSelectorOnMainThread:@selector(His_Data_Finished_not_reload:) withObject:out_dic waitUntilDone:YES];            
         
     }
    
    
    
    
    
}
//輸入開頭與結束日期 取出歷史資料
-(NSMutableDictionary *)Get_hisstory_data_3y{
    
    NSString *urls_his=[[NSString stringWithFormat:@"http://finance.iphone.mobile.yahoo.com/3fc7/chart/symbol/%@/chartdata;range=3y?view=detail&format=json",code] stringByReplacingOccurrencesOfString:@"^" withString:@"%5E"] ;
    NSLog(@"urls=%@",urls_his);
    
    
    //2.轉成 NSURL
    NSURL *url = [NSURL URLWithString:urls_his];   
    
    
    //3.製作request
    //Yahoo Mobile Server 破解指令
    NSMutableURLRequest* request  ;
    request= [XXcrackServerRequest Yahoo_Mobile_Crack_Request:url] ;
    
    
    
    //4.下載data
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];    
    //5.data 資料轉成string
    NSString  *download_string_yahoo;
    download_string_yahoo = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];      
    // NSLog(@"mobile=%@",download_string_yahoo);
    
    NSDictionary *dic_finance =  [[download_string_yahoo JSONValue] objectForKey:@"finance"] ;
    [download_string_yahoo release];
    NSDictionary *dic_Quote=[dic_finance  objectForKey:@"values"];
    
    NSArray *array_Quote=[ dic_Quote  objectForKey:@"value"];         
    
    
    BOOL issetHighLow;
    issetHighLow=NO;               
    
    NSMutableArray *outarray_his_data; //歷史資料
    outarray_his_data=[[[NSMutableArray alloc] init] autorelease];
    
    double his_data_high; // 最大值
    double his_data_low;  // 最小值 
    his_data_low=0;
    his_data_high=0;    
    
    NSDate *last_his_date=[NSDate dateWithTimeIntervalSince1970:9999];
    NSNumber *last_his_close=[NSNumber numberWithFloat: 0 ];         
    
    
    
    for (NSDictionary *dic in array_Quote ) {
      
        //長天期 year
        NSDate *dates;
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"yyyyMMdd"];
        [dateFormatter setTimeZone: [NSTimeZone   timeZoneWithName:timezone]];
        dates = [dateFormatter dateFromString:[dic objectForKey:@"date"] ];
        [dateFormatter release];              
        
        double d_close;
        double d_open;
        double d_high;
        double d_low;
        double d_adj_close;                
        int i_volume;
        d_close=[[dic objectForKey:@"close"]  doubleValue ];                    
        d_open=[[dic objectForKey:@"open"]  doubleValue];
        d_low=[[dic objectForKey:@"low"]  doubleValue ];
        d_high=[[dic objectForKey:@"high"]  doubleValue ];  
        
        d_adj_close=[[dic objectForKey:@"close"]  doubleValue ];                 
        i_volume=[[dic objectForKey:@"volume"]  intValue ];                 
        
        if (d_low==0) {
            d_low=d_close;
        }
        if (d_high==0) {
            d_high=d_close;
        }
        if (d_open==0) {
            d_open=d_close;
        }
        
        NSNumber *close=[NSNumber numberWithDouble:d_close];
        NSNumber *open=[NSNumber numberWithDouble:d_open];                               
        NSNumber *high=[NSNumber numberWithDouble:d_high];                
        NSNumber *low=[NSNumber numberWithDouble:d_low];                     
        NSNumber *volume=[NSNumber numberWithInt:i_volume];                    
        NSNumber *adjclose=[NSNumber numberWithDouble:d_adj_close];                
        
        //比較取出歷史最大值與最小值
        {
            if (issetHighLow==NO) {
                //第一次設定
                his_data_low=d_close;
                his_data_high=d_close;
                issetHighLow=YES;
                
                
                                 
            }
            
            if (d_high>his_data_high) {
                his_data_high=d_high;
            }
            
            if (d_low<his_data_low  ) {
                his_data_low=d_low;
            }  
            
            last_his_date=dates;
            last_his_close=adjclose; //注意此點             
            
        }
        
        
        NSMutableDictionary *dic;
        dic=[[NSMutableDictionary alloc] init];             
        
        [dic setObject:dates forKey: HIS_basic_date ];
        [dic setObject:close forKey:HIS_basic_close];
        [dic setObject:open forKey:HIS_basic_open];
        [dic setObject:high forKey:HIS_basic_high];
        [dic setObject:low forKey:HIS_basic_low];
        [dic setObject:volume forKey:HIS_basic_vol];
        [dic setObject:adjclose forKey:HIS_basic_adjclose];                     
        
        
        
        //NSLog(@"%@",line);                    
        [outarray_his_data addObject:dic];
        [dic release];             
        
        
        /*
         //如果比較短一點的d 則是改用time 
         NSString *urls_his=[[NSString stringWithFormat:@"http://finance.iphone.mobile.yahoo.com/3fc7/chart/symbol/%@/chartdata;range=5d?view=detail&format=json",code] stringByReplacingOccurrencesOfString:@"^" withString:@"%5E"] ;             
         
         NSLog(@"time=%@ ", [dic objectForKey:@"time"]   );  
         */
    }
    
    //將歷史資料檔案陣列 最大值 最小值 存放在Dictionary，用來傳出去
    NSMutableDictionary *out_dic=[[[NSMutableDictionary alloc] init] autorelease];
    [out_dic setObject:code forKey:DB_object_sqlite_basic_code];
    [out_dic setObject:outarray_his_data forKey:@"his_data"];
    [out_dic setObject:[NSNumber numberWithDouble: his_data_high] forKey:@"his_data_high"];
    
    [out_dic setObject:[NSNumber numberWithDouble: his_data_low] forKey:@"his_data_low"];      
    [out_dic setObject:last_his_date forKey:@"last_his_date"];
    [out_dic setObject:last_his_close forKey:@"last_his_close"];
    
    if ([array_Quote count]>0) {
        return out_dic;     
    }
    else {
        return nil;
    }            
          
         
} 

//取出最近五日的資料
-(NSMutableArray *)Get_5d_hisstory_data{
   
    //此段資料可能有誤需要再次檢查
    
    NSLog(@"test===Get_5d_hisstory_data");
    NSString *urls_his=[[NSString stringWithFormat:@"http://finance.iphone.mobile.yahoo.com/3fc7/chart/symbol/%@/chartdata;range=5d?view=detail&format=json",code] stringByReplacingOccurrencesOfString:@"^" withString:@"%5E"] ;
    //NSLog(@"urls=%@",urls_his);
    
    
    //2.轉成 NSURL
    NSURL *url = [NSURL URLWithString:urls_his];   
    
    
    //3.製作request
    //Yahoo Mobile Server 破解指令
    NSMutableURLRequest* request  ;
    request= [XXcrackServerRequest Yahoo_Mobile_Crack_Request:url] ;

    
    
    
    //4.下載data
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];    
    //5.data 資料轉成string
    NSString  *download_string_yahoo;
    download_string_yahoo = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];      
    // NSLog(@"mobile=%@",download_string_yahoo);
    
    NSDictionary *dic_finance =  [[download_string_yahoo JSONValue] objectForKey:@"finance"] ;
    [download_string_yahoo release];
    NSDictionary *dic_Quote=[dic_finance  objectForKey:@"values"];
    
    NSArray *array_Quote=[ dic_Quote  objectForKey:@"value"];         
    
    
    int int_day_now;
    int_day_now=0;
    
    NSMutableArray *RANGE_ARRAY;
    RANGE_ARRAY=[[[NSMutableArray alloc] init] autorelease];
    
    double temp_high;
    temp_high=0;
    double temp_low;
    temp_low=0;
    int temp_vol;
    temp_vol=0;
    double temp_open;
    double temp_close;        
    temp_open=0;
    //temp_close=0;
    if ([array_Quote count]>0) {
        for (NSDictionary *dic in array_Quote ) {
            
            
            NSDate *dates=[NSDate dateWithTimeIntervalSince1970:[[dic objectForKey:@"time"] doubleValue] ];                       
            
            double d_close;
            //double d_open;
            double d_high;
            double d_low;
            //double d_adj_close;                
            int i_volume;
            
            d_close=[[dic objectForKey:@"close"]  doubleValue ];                    
           // d_open=[[dic objectForKey:@"open"]  doubleValue];
            d_low=[[dic objectForKey:@"low"]  doubleValue ];
             
            d_high=[[dic objectForKey:@"high"]  doubleValue ];  
           // d_adj_close=[[dic objectForKey:@"close"]  doubleValue ];                 
            i_volume=[[dic objectForKey:@"volume"]  intValue ];             
            
            
            if (int_day_now !=[self convert_NSDate_to_int:dates] ) {
                //每日的第一筆
                //NSLog(@"time open=%@ %i",dates,[self convert_NSDate_to_int:dates]);
                
                temp_open=d_close;
                temp_close=d_close;
                temp_low=d_close;
                temp_high=d_close;
                temp_vol=i_volume;
                
                
                NSMutableDictionary *add_day_dic=[[NSMutableDictionary alloc] init];
                [RANGE_ARRAY addObject:add_day_dic]; 
                [add_day_dic release];
                
                
                
            }
            else {
                // NSLog(@"time =%@ %i",dates,[self convert_NSDate_to_int:dates]);
                //非第一筆資料
                if ( d_high > temp_high) {
                    temp_high=d_high;
                }
                if (d_low < temp_low) {
                    temp_low=d_low;
                }
                temp_vol=temp_vol+i_volume;
                temp_close=d_close;
            }
            
            [[RANGE_ARRAY objectAtIndex: [RANGE_ARRAY count]-1  ] setObject:dates forKey:HIS_basic_date];                
            [[RANGE_ARRAY objectAtIndex: [RANGE_ARRAY count]-1  ] setObject:[NSNumber numberWithDouble: temp_close] forKey:HIS_basic_close];
            [[RANGE_ARRAY objectAtIndex: [RANGE_ARRAY count]-1  ] setObject:[NSNumber numberWithDouble: temp_open] forKey:HIS_basic_open]; 
            [[RANGE_ARRAY objectAtIndex: [RANGE_ARRAY count]-1  ] setObject:[NSNumber numberWithDouble: temp_high] forKey:HIS_basic_high]; 
            [[RANGE_ARRAY objectAtIndex: [RANGE_ARRAY count]-1  ] setObject:[NSNumber numberWithDouble: temp_low] forKey:HIS_basic_low];                     
            [[RANGE_ARRAY objectAtIndex: [RANGE_ARRAY count]-1  ] setObject:[NSNumber numberWithDouble: temp_vol] forKey:HIS_basic_vol];                     
            [[RANGE_ARRAY objectAtIndex: [RANGE_ARRAY count]-1  ] setObject:[NSNumber numberWithDouble: temp_close] forKey:HIS_basic_adjclose];                
            
            
            
            int_day_now=[self convert_NSDate_to_int:dates];
            
        }
        
        /*
         for (NSMutableDictionary *DD in RANGE_ARRAY  ) {
         NSLog(@"ddf=%@",DD);
         }
         */
        
        return RANGE_ARRAY;           
        
        
    }
    else {
        return nil;
    }
     
    
    
    //yahoo_web 的範例 目前不會使用
    /*
    {
        
        
        NSString *urls_his=[NSString stringWithFormat:@"http://chartapi.finance.yahoo.com/instrument/1.0/%@/chartdata;type=quote;range=5d/csv/",code];
        
        //2.轉成 NSURL
        NSURL *url = [NSURL URLWithString:urls_his];   
        
        
        //3.製作request
        NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:url]
                                        autorelease];
        
        [request setValue:Yahoo_web_User_Agent forHTTPHeaderField:@"User-Agent"];
        
        //4.下載data
        NSURLResponse* response = nil;
        NSError* error = nil;
        NSData* data = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:&response
                                                         error:&error];    
        //5.data 資料轉成string
        NSString  *download_string_yahoo;
        download_string_yahoo = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];    
        
        // NSLog(@"download_string_yahoo=%@",download_string_yahoo);
        NSArray *data_array=[download_string_yahoo  componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];   
        
        if ([data_array count]>1) {
            BOOL begin_read_data;
            begin_read_data=NO;
            
            //開始讀取日內資料
            BOOL write_open;
            BOOL write_close;
            int write_day;
            write_open=NO;
            write_close=YES;
            write_day=0;
            
            double open;
            double high;
            double low;
            double close;
            double volume;
            open=0;
            high=0;
            close=0;
            low=0;
            volume=0;
            
            NSMutableArray *RANGE_ARRAY;
            RANGE_ARRAY=[[[NSMutableArray alloc] init] autorelease];
            
            
            
            for (NSString *line in data_array  ) {
                // NSLog(@"%@",line);
                if ([line hasPrefix:@"range:"]) {
                    
                    NSString *date_timeS_timeE;
                    date_timeS_timeE=  [line stringByReplacingOccurrencesOfString:@"range:" withString:@""];
                    NSArray *date_timeS_timeE_array;
                    date_timeS_timeE_array = [date_timeS_timeE componentsSeparatedByString:@","]   ;              
                    if ([ date_timeS_timeE_array count ]==3) {
                        
                        NSMutableDictionary *dd=[[NSMutableDictionary alloc] init];
                        [dd setObject:[date_timeS_timeE_array objectAtIndex:0] forKey:@"day"];
                        [dd setObject:[date_timeS_timeE_array objectAtIndex:1] forKey:@"start"];
                        [dd setObject:[date_timeS_timeE_array objectAtIndex:2] forKey:@"end"];                
                        [RANGE_ARRAY addObject:dd];
                        [dd release];
                    }
                    
                    
                }
                
                
                if (begin_read_data==YES) {
                    //Timestamp,close,high,low,open,volume
                    
                    NSArray *data;
                    data = [line componentsSeparatedByString:@","]   ;
                    int timestarmp;
                    timestarmp=[[data objectAtIndex:0] intValue];
                    
                    for (NSMutableDictionary *rd in RANGE_ARRAY) {
                        int start;
                        int end;
                        start=[[rd objectForKey:@"start"] intValue];
                        end =[[rd objectForKey:@"end"] intValue];
                        
                        if (start<=timestarmp && timestarmp<=end) {
                            //表示剛好符合再區間內
                            
                            if (write_day!=[[rd objectForKey:@"day"] intValue]) {
                                //NSLog(@"right write_open=%@",[rd objectForKey:@"day"]);
                                close=[[data objectAtIndex:1] doubleValue];
                                high=[[data objectAtIndex:2] doubleValue];
                                low=[[data objectAtIndex:3] doubleValue]; 
                                open=[[data objectAtIndex:4] doubleValue];  
                                volume=[[data objectAtIndex:5] doubleValue]; 
                            }
                            else {
                                //NSLog(@"right =%@",[rd objectForKey:@"day"]);
                                close=[[data objectAtIndex:1] doubleValue];
                                if (high <=[[data objectAtIndex:2] doubleValue]) {
                                    high=[[data objectAtIndex:2] doubleValue];
                                }
                                if (low>=[[data objectAtIndex:3] doubleValue]) {
                                    low=[[data objectAtIndex:3] doubleValue];
                                }
                                volume=volume+ [[data objectAtIndex:5] doubleValue];
                            }
                            
                            
                            write_day=[[rd objectForKey:@"day"] intValue];                      
                            
                            //將資料存到 rd array
                            NSDate *dates;
                            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
                            [dateFormatter setDateFormat:@"yyyyMMdd"];
                            [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
                            dates = [dateFormatter dateFromString:[rd objectForKey:@"day"] ];
                            [dateFormatter release];                      
                            
                            [rd setObject:dates forKey:HIS_basic_date];                    
                            [rd setObject:[NSNumber numberWithDouble: close] forKey:HIS_basic_close];
                            [rd setObject:[NSNumber numberWithDouble: open] forKey:HIS_basic_open]; 
                            [rd setObject:[NSNumber numberWithDouble: high] forKey:HIS_basic_high]; 
                            [rd setObject:[NSNumber numberWithDouble: low] forKey:HIS_basic_low];                     
                            [rd setObject:[NSNumber numberWithDouble: volume] forKey:HIS_basic_vol];                     
                            [rd setObject:[NSNumber numberWithDouble: close] forKey:HIS_basic_adjclose];                    
                            
                        }
                        
                        
                        
                        
                    }
                    
                    
                }
                
                if ([line hasPrefix:@"volume:"]) {
                    begin_read_data=YES;
                }        
                
            }
            
            NSLog(@"RANGE_ARRAY=%@",RANGE_ARRAY  );
            
            
            return RANGE_ARRAY;        
        }
        else {
            return nil;
        }
        
    
    }
    */
        
    
}

//輸入NSDate 轉出int
-(int)convert_NSDate_to_int:(NSDate *)nsdate{
    NSDateFormatter *dateFormatters = [[[NSDateFormatter alloc] init] autorelease];
    dateFormatters.dateFormat = @"yyyyMMdd";
    
    int  timeStamp_file_last_date = [[dateFormatters stringFromDate:nsdate] intValue];      
    
    return timeStamp_file_last_date;
}


@end
